﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;

namespace VK.Comm
{
    public static class Util
    {
        #region === NumberToEnglish ===
        public static string FormatEnglishByNumber(int number)
        {
            string result = string.Empty;
            string[] numbers = new string[10] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
            string numberstr = number.ToString();
            IEnumerator numberEnum = numberstr.GetEnumerator();
            int charCount = 0;
            while (numberEnum.MoveNext())
            {
                charCount++;
                result += numbers[int.Parse(numberEnum.Current.ToString())];
            }
            return result;
        }
        #endregion

        #region === DateTime ===
        public static DateTime DateTimeNull = DateTime.Parse("1900-01-01");

        public static DateTime ConverDateTime(object datetime)
        {
            DateTime result = DateTimeNull;
            if (datetime == null && datetime == DBNull.Value) return result;
            if (datetime.GetType().Name == "String")
            {
                if (datetime != null && datetime.ToString() != string.Empty)
                {
                    result = DateTime.Parse(datetime.ToString());
                }
            }
            else
            {
                if (datetime != DBNull.Value)
                {
                    result = (DateTime)datetime;
                }
            }
            return result;
        }

        public static string FormatDateTime(DateTime datetime, DateTimeStyle dateTimeStyle)
        {
            string result = string.Empty;
            if (datetime != DateTimeNull)
            {
                switch (dateTimeStyle)
                {
                    case DateTimeStyle.ShortDate: result = datetime.ToShortDateString(); break;
                    case DateTimeStyle.LongDate: result = datetime.ToLongDateString(); break;
                    case DateTimeStyle.ShortTime: result = datetime.ToShortTimeString(); break;
                    case DateTimeStyle.LongTime: result = datetime.ToLongTimeString(); break;
                    case DateTimeStyle.ShortDate2: result = datetime.ToString("yyyy-MM-dd"); break;
                    case DateTimeStyle.ShortDate3: result = datetime.ToString("MM-dd"); break;
                    case DateTimeStyle.Null: result = datetime.ToString(); break;
                }
            }
            return result;
        }
        #endregion

        #region === Query ===
        public static string GetQueryString(string name)
        {
            string valueStr = HttpContext.Current.Request.QueryString[name];
            return valueStr;
        }

        public static int GetQueryInt(string name)
        {
            int valueInt = 0;
            string valueStr = HttpContext.Current.Request.QueryString[name];
            if (!string.IsNullOrEmpty(valueStr))
            {
                if (RegexStr.CheckNum(valueStr))
                {
                    valueInt = int.Parse(valueStr);
                }
            }
            return valueInt;
        }

        public static double GetQueryDouble(string name)
        {
            double valueDouble = 0;
            string valueStr = HttpContext.Current.Request.QueryString[name];
            if (!string.IsNullOrEmpty(valueStr))
            {
                valueDouble = double.Parse(valueStr);
            }
            return valueDouble;
        }
        #endregion

        #region === RouteData ===
        public static string GetRouteDataString(string name)
        {
            string valueStr = null;
            if (HttpContext.Current.Request.RequestContext.RouteData.Values[name] != null)
            {
                valueStr = HttpContext.Current.Request.RequestContext.RouteData.Values[name].ToString();
            }
            return valueStr;
        }

        public static int GetRouteDataInt(string name)
        {
            int valueInt = 0; string valueStr = null;
            if (HttpContext.Current.Request.RequestContext.RouteData.Values[name] != null)
            {
                valueStr = HttpContext.Current.Request.RequestContext.RouteData.Values[name].ToString();
            }
            if (!string.IsNullOrEmpty(valueStr))
            {
                if (RegexStr.CheckNum(valueStr))
                {
                    valueInt = int.Parse(valueStr);
                }
            }
            return valueInt;
        }

        public static double GetRouteDataDouble(string name)
        {
            double valueDouble = 0; string valueStr = null;
            if (HttpContext.Current.Request.RequestContext.RouteData.Values[name] != null)
            {
                valueStr = HttpContext.Current.Request.RequestContext.RouteData.Values[name].ToString();
            }
            if (!string.IsNullOrEmpty(valueStr))
            {
                valueDouble = double.Parse(valueStr);
            }
            return valueDouble;
        }
        #endregion

        #region === From ===
        public static string GetFormString(string name)
        {
            string valueStr = HttpContext.Current.Request.Form[name];
            return valueStr;
        }

        public static int GetFormInt(string name)
        {
            int valueInt = 0;
            string valueStr = HttpContext.Current.Request.Form[name];
            if (!string.IsNullOrEmpty(valueStr))
            {
                valueStr = valueStr.Trim();
                if (RegexStr.CheckNum(valueStr))
                {
                    valueInt = int.Parse(valueStr);
                }
            }
            return valueInt;
        }

        public static decimal GetFormDecimal(string name)
        {
            decimal valueDecimal = 0;
            string valueStr = HttpContext.Current.Request.Form[name].Trim();
            if (!string.IsNullOrEmpty(valueStr))
            {
                valueDecimal = decimal.Parse(valueStr);
            }
            return valueDecimal;
        }
        #endregion

        #region === Cookie ===
        public static string GetCookieString(string name)
        {
            string valueStr = HttpContext.Current.Request.Cookies[name].Value;
            return valueStr;
        }

        public static int GetCookieInt(string name)
        {
            int valueInt = 0;
            string valueStr = HttpContext.Current.Request.Cookies[name].Value;
            if (!string.IsNullOrEmpty(valueStr))
            {
                if (RegexStr.CheckNum(valueStr))
                {
                    valueInt = int.Parse(valueStr);
                }
            }
            return valueInt;
        }
        #endregion

        #region === GetTextNumber ===
        public static decimal GetTextDecimal(string text)
        {
            decimal valueDecimal = 0;
            string valueStr = text.Trim();
            if (!string.IsNullOrEmpty(valueStr))
            {
                valueDecimal = decimal.Parse(valueStr);
            }
            return valueDecimal;
        }

        public static int GetTextInt(string text)
        {
            int valueInt = 0;
            string valueStr = text.Trim();
            if (!string.IsNullOrEmpty(valueStr))
            {
                valueInt = int.Parse(valueStr);
            }
            return valueInt;
        }

        public static string ViewNumber(string number)
        {
            return ViewNumber(number, string.Empty, string.Empty);
        }

        public static string ViewNumber(string number, string append)
        {
            return ViewNumber(number, string.Empty, append);
        }

        public static string ViewNumber(string number, string prepend, string append)
        {
            string valueStr = string.Empty;
            if (number != "0" && number != "0.00" && number != "0.0000")
            {
                valueStr = prepend + number.ToString() + append;
            }
            return valueStr;
        }
        #endregion

        #region 按日期生成编号--20字符
        public static string GetDateTimeNO()
        {
            string result = string.Empty;
            result = DateTime.Now.ToString("yyyyMMddhhmmssffffff");
            return result;
        }
        #endregion

        #region 截取字符串
        public static string CutString(string str, int length, CutStyle cutStyle)
        {
            string newString = string.Empty;
            if (!string.IsNullOrEmpty(str))
            {
                if (str.Length > length)
                {
                    switch (cutStyle)
                    {
                        case CutStyle.Empty:
                            newString = str.Substring(0, length);
                            break;
                        case CutStyle.Ellipsis:
                            newString = str.Substring(0, length) + "...";
                            break;
                    }
                }
                else
                {
                    newString = str;
                }
            }
            return newString;
        }
        #endregion

        #region 生成N位随机数
        public static string GetRandomNumber(int codeCount)
        {
            string strChoice = "0,1,2,3,4,5,6,7,8,9";
            string[] strResult = strChoice.Split(new Char[] { ',' });
            string strReturn = "";
            Random rnd = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                int j = rnd.Next(strResult.Length);//随机数不能大于数组的长度
                strReturn = strReturn + strResult[j].ToString();
            }
            return strReturn;
        }
        #endregion

        #region 除去所有在HTML元素中标记
        public static string StripHTML(string strHtml)
        {
            string strOutput = strHtml;
            Regex regex = new Regex(@"<[^>]+>|]+>");
            strOutput = regex.Replace(strOutput, "");
            strOutput = strOutput.Replace(" ", "");
            strOutput = strOutput.Replace("&nbsp;", "");
            return strOutput;
        }
        #endregion

        #region 获得当前绝对路径
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
        #endregion

        #region 获取域名
        /// <summary>
        /// 获取当前全部域名Url（如：http://www.shopkv.com:8080/）
        /// </summary>
        /// <returns></returns>
        public static string GetDomain()
        {
            string result = string.Empty;
            result = "http://" + HttpContext.Current.Request.Url.Host.ToString() + ":" + HttpContext.Current.Request.Url.Port + "/";
            return result;
        }
        #endregion

        #region 汉字拼音转换
        /// <summary> 
        /// 得到一个汉字的拼音第一个字母，如果是一个英文字母则直接返回大写字母 
        /// </summary> 
        /// <param name="CnChar">单个汉字</param> 
        /// <returns>单个大写字母</returns> 
        public static string GetCharSpellCode(string CnChar)
        {
            long iCnChar;

            byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar);

            //如果是字母，则直接返回 
            if (ZW.Length == 1)
            {
                return CnChar.ToUpper();
            }
            else
            {
                // get the array of byte from the single char 
                int i1 = (short)(ZW[0]);
                int i2 = (short)(ZW[1]);
                iCnChar = i1 * 256 + i2;
            }

            //expresstion 
            //table of the constant list 
            // 'A'; //45217..45252 
            // 'B'; //45253..45760 
            // 'C'; //45761..46317 
            // 'D'; //46318..46825 
            // 'E'; //46826..47009 
            // 'F'; //47010..47296 
            // 'G'; //47297..47613 

            // 'H'; //47614..48118 
            // 'J'; //48119..49061 
            // 'K'; //49062..49323 
            // 'L'; //49324..49895 
            // 'M'; //49896..50370 
            // 'N'; //50371..50613 
            // 'O'; //50614..50621 
            // 'P'; //50622..50905 
            // 'Q'; //50906..51386 

            // 'R'; //51387..51445 
            // 'S'; //51446..52217 
            // 'T'; //52218..52697 
            //没有U,V 
            // 'W'; //52698..52979 
            // 'X'; //52980..53640 
            // 'Y'; //53689..54480 
            // 'Z'; //54481..55289 

            // iCnChar match the constant 
            if ((iCnChar >= 45217) && (iCnChar <= 45252))
            {
                return "A";
            }
            else if ((iCnChar >= 45253) && (iCnChar <= 45760))
            {
                return "B";
            }
            else if ((iCnChar >= 45761) && (iCnChar <= 46317))
            {
                return "C";
            }
            else if ((iCnChar >= 46318) && (iCnChar <= 46825))
            {
                return "D";
            }
            else if ((iCnChar >= 46826) && (iCnChar <= 47009))
            {
                return "E";
            }
            else if ((iCnChar >= 47010) && (iCnChar <= 47296))
            {
                return "F";
            }
            else if ((iCnChar >= 47297) && (iCnChar <= 47613))
            {
                return "G";
            }
            else if ((iCnChar >= 47614) && (iCnChar <= 48118))
            {
                return "H";
            }
            else if ((iCnChar >= 48119) && (iCnChar <= 49061))
            {
                return "J";
            }
            else if ((iCnChar >= 49062) && (iCnChar <= 49323))
            {
                return "K";
            }
            else if ((iCnChar >= 49324) && (iCnChar <= 49895))
            {
                return "L";
            }
            else if ((iCnChar >= 49896) && (iCnChar <= 50370))
            {
                return "M";
            }

            else if ((iCnChar >= 50371) && (iCnChar <= 50613))
            {
                return "N";
            }
            else if ((iCnChar >= 50614) && (iCnChar <= 50621))
            {
                return "O";
            }
            else if ((iCnChar >= 50622) && (iCnChar <= 50905))
            {
                return "P";
            }
            else if ((iCnChar >= 50906) && (iCnChar <= 51386))
            {
                return "Q";
            }
            else if ((iCnChar >= 51387) && (iCnChar <= 51445))
            {
                return "R";
            }
            else if ((iCnChar >= 51446) && (iCnChar <= 52217))
            {
                return "S";
            }
            else if ((iCnChar >= 52218) && (iCnChar <= 52697))
            {
                return "T";
            }
            else if ((iCnChar >= 52698) && (iCnChar <= 52979))
            {
                return "W";
            }
            else if ((iCnChar >= 52980) && (iCnChar <= 53640))
            {
                return "X";
            }
            else if ((iCnChar >= 53689) && (iCnChar <= 54480))
            {
                return "Y";
            }
            else if ((iCnChar >= 54481) && (iCnChar <= 55289))
            {
                return "Z";
            }
            else return ("?");
        }
        #endregion

        #region JavaScript辅助方法
        public static string WrapJavaScript(string content)
        {
            StringBuilder result = new StringBuilder();
            result.Append("<script language='javascript' type='text/javascript'>");
            result.Append(content);
            result.Append("</script>");
            return result.ToString();
        }
        #endregion

        #region 清空控件内容
        public static void ClearControl(ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                switch (control.GetType().FullName)
                {
                    case "System.Web.UI.WebControls.DropDownList":
                        DropDownList ddl = (control as DropDownList);
                        if (ddl.Items.Count > 0)
                        {
                            ddl.SelectedIndex = 0;
                        }
                        break;
                    case "System.Web.UI.WebControls.TextBox":
                        (control as TextBox).Text = string.Empty;
                        break;
                }
            }
        }
        #endregion

        //根据Url地址得到网页的html源码
        public static string GetWebHtml(string url)
        {
            string strResult = "";
            WebClient wc = new WebClient();
            try
            {
                if (url == null || url.Trim() == "")
                    strResult = "";
                wc.Credentials = CredentialCache.DefaultCredentials;
                Byte[] pageData = wc.DownloadData(url);

                strResult = Encoding.UTF8.GetString(pageData);
            }
            catch
            {
                strResult = "";
            }
            finally
            {
                wc.Dispose();
            }
            return strResult;
        }

        public static string VisibleString(string originStr)
        {
            if (originStr.Length > 9)
                return originStr.Substring(0, 9) + "...";
            return originStr;
        }

        public static string GetHostUrl(string host, int port)
        {
            string url = "http://" + host;
            if (port != 80)
            {
                url += ":" + port;
            }

            return url;
        }
    }

    public enum CutStyle
    {
        Empty = 1,
        Ellipsis = 2
    }

    public enum DateTimeStyle
    {
        /// <summary>
        /// 2012/1/9
        /// </summary>
        ShortDate = 1,
        LongDate = 2,
        ShortTime = 3,
        LongTime = 4,
        /// <summary>
        /// 2012-1-9
        /// </summary>
        ShortDate2 = 5,
        ShortDate3 = 6,
        Null = 7
    }

   
}
